<?php
/**
 * @name /www/donations/index.php
 * @author Michael Foss <michael@mikefoss.com>
 * @version 2011.03.31
 *
 * Shows donations.
 */

// Sets up configuration settings and includes libraries.
require_once('_ini.php');

ReqLib('/lib/private/User.php');
ReqLib('/lib/private/DonatedItem.php');
ReqLib('/lib/private/ItemSearchWidget.php');

function DefinePreload() {
  $user = new User();
  $user->Load($_SESSION['userId']);
  if (!$user->UserId) {
    header('location: ' . _webroot('/login_register.php?pagereq=/donations/index.php'));
    die();
  }
  $action = $_POST['Action'];
  if ($action) {
    require_once('controller.php');
    DoController($action, $user);
  }
  else
    require_once('model.php');
}

function DefineHeader() {
?><script type="text/javascript" src="view.js"></script>
<style type="text/css">
<?
  $user = new User();
  $user->Load($_SESSION['userId']);
  // If the user is not an admin, hide all Admin classes
  if (!$user->HasRole('Administrator'))
    println('  .Admin, #__A,');
?>  #DonationDialog,
  #DonatedItemTemplate,
  #DonatedItemsTemplate,
  #DonatedItemDialog {
    display: none;
  }
</style>
<script type="text/javascript">
  $(function() {
    $('#BecomeDonor')
      .button({
        label: 'Become Donor'
      })
      .click(function() {
        window.location = '<?=_webroot('/become-donor.php') ?>';
      });
  });
</script>
<title>Donations</title>
<?
}

/**
 * Defines page content.
 *
 */
function DefineContent() {
  println('<h1>Donations</h1>');
  $user = new User();
  $user->Load($_SESSION['userId']);
  $isAdmin = $user->HasRole('administrator');
  $isDonor = $user->HasRole('donator');
  if (!$isAdmin && !$isDonor)
    DisplayStaticContent();
  else {
    $donations = GetDonations($user, $isAdmin);
    BuildTable($donations, $isAdmin);
    BuildEditDialog($isAdmin);
?><div id="MessageBox"></div>
<?
  }
}

function GetDonations($user, $isAdmin) {
  if ($isAdmin)
    $donations = Donation::GetDonations();
  else {
    $ids = Donation::GetDonationIdsByUserId($user->UserId);
    $donations = array();
    if (count($ids)) {
      $db = new DB();
      foreach ($ids as $id) {
        $d = new Donation();
        $d->Load($id);
        //$d->DateDonated = date('m/d/y', $d->DateDonated);
        $donations[] = $d;
      }
    }
  }
  return $donations;
}

function DisplayStaticContent() {
?><p>
  It looks like you aren't a donor. In order to submit donations, you must be
  signed up to be a donor.
</p>
<p>
  <a id="BecomeDonor"></a>
</p>
<?
}

// Launches the page; without this, nothing happens.
require_once('_loader.php');